$(function () {
    $.menuSelector('#system_role');

    $('#data-form').validationEngine('attach', {
        validateNonVisibleFields: true,
        scroll: false,
        maxErrorsPerField: 1
    });

    var _app = {
        ztree: null,
        loadZTree: function () {
            var roleId = $('#roleId').val();
            if (!roleId) {
                roleId = 0;
            }

            $.ajax({
                url: g.ctx + '/system/role/resources/' + roleId,
                beforeSend: function () {
                    $('#tree').html('正在加载...');
                },
                complete: function () {

                },
                success: function (rets) {
                    Ifonly.ApiMessage.process(rets, function (rets) {
                        if (rets.data && rets.data.length > 0) {
                            $('#resourceIds').val(rets.message);
                            _app.ztree = new ZTree('#tree', {
                                check: {
                                    enable: true
                                },
                                callback: {
                                    onCheck: _app.onCheck
                                }
                            }, rets.data);
                        }
                    });
                }
            });
        },
        onCheck: function () {
            $('#resourceIds').val(_app.getSelectIds());
        },
        getSelectIds: function () {
            var ids = [];
            var treeObj = _app.ztree.ztree;
            var nodes = treeObj.getCheckedNodes(true);
            $.each(nodes, function (i, o) {
                if (o.id != 0) {
                    ids.push(o.id);
                }
            });
            return ids.join(',');
        }
    };

    /**
     * 资源 Ztree 处理
     */
    (function () {
        _app.loadZTree();
    })();

});

function selectResourceIds(field, rules, i, options) {
    if (!field.val()) {
        return "请选择资源";
    }
}